#include "SocketRunnable.hpp"
#include "TcpSocket.hpp"
#include <stdio.h>

void SocketRunnable::run() {
    printf("liaolijiang is coming TcpClient.cpp\n");
    // SocketRunnable *pSocketRunnable = new SocketRunnable();
    // epicsThread * pSocketRunnableThread = new epicsThread(*pSocketRunnable, "SocketRunnable", epicsThreadGetStackSize(epicsThreadStackMedium));
    // pSocketRunnableThread->start();

	DataRingConsumeThread *runnable = new DataRingConsumeThread(pTcpSocketDataInfo);
	pDataRingConsumeThread = new epicsThread(*runnable, "DataRingConsumeThread", epicsThreadGetStackSize(epicsThreadStackMedium));
	pDataRingConsumeThread->start();
	
    unsigned char buffer[1024];
    while(do_recv) {
    	epicsThreadSleep(0.1);
		memset(buffer, 0x00, 1024);
    	int recvLength = client.receive(buffer, 1024);
    	#if 0
    	for (int i = 0; i < recvLength; ++i)
    	{
    		/* code */
    		printf("data[%d]= %x \n", i, buffer[i]);
    	}
		#else 
		if (recvLength > 0) {
			epicsMutexLock(pTcpSocketDataInfo->mutex);
			int nUsed = epicsRingBytesUsedBytes(pTcpSocketDataInfo->ring);
			//printf("recieve thread ring[%ld] -- nUsed is %d\n",pTcpSocketDataInfo->ring, nUsed);
			
			epicsRingBytesPut(pTcpSocketDataInfo->ring, (char *)buffer, recvLength);
			nUsed = epicsRingBytesUsedBytes(pTcpSocketDataInfo->ring);
			//printf("epicsRingBytesPut after nUsed is %dpTcpSocketDataInfo->ring is %d\n", nUsed, pTcpSocketDataInfo->ring);
			epicsMutexUnlock(pTcpSocketDataInfo->mutex);
			
			}else {
				printf("recive null charater ......");
			}
    	}
    	#endif
    	//pFilter->ringWrite(buffer, recvLength);
    }

SocketRunnable::SocketRunnable(TcpSocketDataInfo *pTcpSocketDataInfo):pTcpSocketDataInfo(pTcpSocketDataInfo),do_recv(true) {
	client = TcpClient();
	//pFilter = new NeutronPulseFilter();
}
